<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="zh-CN" dir="ltr">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <title>Mybatis分页-利用Mybatis Generator插件生成基于数据库方言的分页语句，统计记录总数 - 迷失代码 - ITeye技术网站</title>
    <meta name="description" content="   	众所周知，Mybatis本身没有提供基于数据库方言的分页功能，而是基于JDBC的游标分页，很容易出现性能问题。网上有很多分页的解决方案，不外乎是基于Mybatis本机的插件机制，通过拦截Sql做分页。但是在像Oracle这样的数据库上，拦截器生成的Sql语句没有变量绑定，而且每次语句的都要去拦截，感觉有点浪费性能。  	Mybatis Generator是Mybatis的代码生成工具，可以生 ..." />
    <meta name="keywords" content="Mybatis 分页 Mybatis Generator 插件 Mybatis分页-利用Mybatis Generator插件生成基于数据库方言的分页语句，统计记录总数" />
    <link rel="shortcut icon" href="/images/favicon.ico" type="image/x-icon" />
    <link rel="search" type="application/opensearchdescription+xml" href="/open_search.xml" title="ITeye" />
    <link href="/rss" rel="alternate" title="迷失代码" type="application/rss+xml" />
    <link href="http://www.iteye.com/stylesheets/blog.css?1384928085" media="screen" rel="stylesheet" type="text/css" />
<link href="http://www.iteye.com/stylesheets/themes/blog/blue.css?1326191326" media="screen" rel="stylesheet" type="text/css" />
    <script src="http://www.iteye.com/javascripts/application.js?1358214518" type="text/javascript"></script>
    <script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-535605-1']);
  _gaq.push(['_setDomainName', 'iteye.com']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>


      <link href="http://www.iteye.com/javascripts/syntaxhighlighter/SyntaxHighlighter.css?1348819953" media="screen" rel="stylesheet" type="text/css" />
  <script src="http://www.iteye.com/javascripts/syntaxhighlighter/shCoreCommon.js?1325907333" type="text/javascript"></script>
<script src="http://www.iteye.com/javascripts/hotkey.js?1324994303" type="text/javascript"></script>
  <script src="http://www.iteye.com/javascripts/code_favorites.js?1358214518" type="text/javascript"></script>
<script src="http://www.iteye.com/javascripts/weiboshare.js?1324994303" type="text/javascript"></script>
  </head>
  <body>
    <div id="header">
      <div id="blog_site_nav">
  <a href="http://www.iteye.com/" class="homepage">首页</a>
  <a href="http://www.iteye.com/news">资讯</a>
  <a href="http://www.iteye.com/magazines">精华</a>
  <a href="http://www.iteye.com/forums">论坛</a>
  <a href="http://www.iteye.com/ask">问答</a>
  <a href="http://www.iteye.com/blogs">博客</a>
  <a href="http://www.iteye.com/blogs/subjects">专栏</a>
  <a href="http://www.iteye.com/groups">群组</a>
  <a href="#" onclick="return false;" id="msna"><u>更多</u> <small>▼</small></a>
  <div class="quick_menu" style="display:none;">
    <a target="_blank" href="http://job.iteye.com/iteye">招聘</a>
    <a href="http://www.iteye.com/search">搜索</a>
  </div>
</div>

      <div id="user_nav">
      <a href="/login" class="welcome" title="登录">您还未登录 !</a>
    <a href="/login">登录</a>
    <a href="/signup" class="nobg">注册</a>
  </div>

    </div>

    <div id="page">
      <div id="branding" class="clearfix">
        <div id="blog_name">
          <h1><a href="/">迷失代码</a></h1>
        </div>
        <div id='fd'></div>
        <div id="blog_navbar">
          <ul>
            <li class='blog_navbar_for'><a href="http://ufopw.iteye.com"><strong>博客</strong></a></li>
            <li ><a href="/weibo">微博</a></li>
            <li ><a href="/album">相册</a></li>
            <li ><a href="/link">收藏</a></li>
            <li ><a href="/blog/guest_book">留言</a></li>
            <li ><a href="/blog/profile">关于我</a></li>
          </ul>
    
          <div class="search">
            <form action="/blog/search" method="get">
              <input class="search_text" id="query" name="query" style="margin-left: 10px;width: 110px;" type="text" value="" />
              <input class="submit_search" type="submit" value="" />
            </form>
          </div> 
          <div id="fd"></div>         
        </div>
      </div>
      
      <div id="content" class="clearfix">
        <div id="main">
          



          


<div class="h-entry" style='display:none'>
  <a href="http://ufopw.iteye.com" class="p-author" target="_blank">ufopw</a>
</div>


<div class="blog_main">
  <div class="blog_title">
    <h3>
      <a href="/blog/1289274">Mybatis分页-利用Mybatis Generator插件生成基于数据库方言的分页语句，统计记录总数</a>
      <em class="actions">      </em>
    </h3>
    <ul class='blog_categories'><strong>博客分类：</strong> <li><a href="/category/59841">Java</a></li> </ul>
        <div class='news_tag'><a href="http://www.iteye.com/blogs/tag/Mybatis%20%E5%88%86%E9%A1%B5%20Mybatis%20Generator%20%E6%8F%92%E4%BB%B6">Mybatis 分页 Mybatis Generator 插件</a></div>
  </div>

  <div id="blog_content" class="blog_content">
    <p> </p>
<p><span style="white-space: pre;">	</span>众所周知，Mybatis本身没有提供基于数据库方言的分页功能，而是基于JDBC的游标分页，很容易出现性能问题。网上有很多分页的解决方案，不外乎是基于Mybatis本机的插件机制，通过拦截Sql做分页。但是在像Oracle这样的数据库上，拦截器生成的Sql语句没有变量绑定，而且每次语句的都要去拦截，感觉有点浪费性能。</p>
<p><span style="white-space: pre;">	</span>Mybatis Generator是Mybatis的代码生成工具，可以生成大部分的查询语句。</p>
<p><span style="white-space: pre;">	</span>本文提供的分页解决方案是新增Mybatis Generator插件，在用Mybatis Generator生成Mybatis代码时，直接生成基于数据库方言的Sql语句，解决Oralce等数据库的变量绑定，且无需使用Mybatis拦截器去拦截语句判断分页。</p>
<p><span style="white-space: pre;">	</span>一、编写Mybatis Generator Dialect插件</p>
<p><span style="white-space: pre;">	</span><span style="white-space: pre; background-color: #fafafa;">/**</span></p>
<pre class="java" name="code"> * Copyright (C) 2011 Tgwoo Inc.
 * http://www.tgwoo.com/
 */
package com.tgwoo.core.dao.plugin;

import java.util.List;

import org.mybatis.generator.api.CommentGenerator;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.api.dom.java.JavaVisibility;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.api.dom.java.Parameter;
import org.mybatis.generator.api.dom.java.TopLevelClass;
import org.mybatis.generator.api.dom.xml.Attribute;
import org.mybatis.generator.api.dom.xml.Document;
import org.mybatis.generator.api.dom.xml.TextElement;
import org.mybatis.generator.api.dom.xml.XmlElement;

/**
 * @author pan.wei
 * @date 2011-11-30 下午08:36:11
 */
public class OraclePaginationPlugin extends PluginAdapter {

	@Override
	public boolean modelExampleClassGenerated(TopLevelClass topLevelClass,
			IntrospectedTable introspectedTable) {
		// add field, getter, setter for limit clause
		addPage(topLevelClass, introspectedTable, "page");
		return super.modelExampleClassGenerated(topLevelClass,
				introspectedTable);
	}

	@Override
	public boolean sqlMapDocumentGenerated(Document document,
			IntrospectedTable introspectedTable) {
		XmlElement parentElement = document.getRootElement();

		// 产生分页语句前半部分
		XmlElement paginationPrefixElement = new XmlElement("sql");
		paginationPrefixElement.addAttribute(new Attribute("id",
				"OracleDialectPrefix"));
		XmlElement pageStart = new XmlElement("if");
		pageStart.addAttribute(new Attribute("test", "page != null"));
		pageStart.addElement(new TextElement(
				"select * from ( select row_.*, rownum rownum_ from ( "));
		paginationPrefixElement.addElement(pageStart);
		parentElement.addElement(paginationPrefixElement);

		// 产生分页语句后半部分
		XmlElement paginationSuffixElement = new XmlElement("sql");
		paginationSuffixElement.addAttribute(new Attribute("id",
				"OracleDialectSuffix"));
		XmlElement pageEnd = new XmlElement("if");
		pageEnd.addAttribute(new Attribute("test", "page != null"));
		pageEnd.addElement(new TextElement(
				"&lt;![CDATA[ ) row_ ) where rownum_ &gt; #{page.begin} and rownum_ &lt;= #{page.end} ]]&gt;"));
		paginationSuffixElement.addElement(pageEnd);
		parentElement.addElement(paginationSuffixElement);

		return super.sqlMapDocumentGenerated(document, introspectedTable);
	}

	@Override
	public boolean sqlMapSelectByExampleWithoutBLOBsElementGenerated(
			XmlElement element, IntrospectedTable introspectedTable) {

		XmlElement pageStart = new XmlElement("include"); //$NON-NLS-1$   
		pageStart.addAttribute(new Attribute("refid", "OracleDialectPrefix"));
		element.getElements().add(0, pageStart);

		XmlElement isNotNullElement = new XmlElement("include"); //$NON-NLS-1$   
		isNotNullElement.addAttribute(new Attribute("refid",
				"OracleDialectSuffix"));
		element.getElements().add(isNotNullElement);

		return super.sqlMapUpdateByExampleWithoutBLOBsElementGenerated(element,
				introspectedTable);
	}

	/**
	 * @param topLevelClass
	 * @param introspectedTable
	 * @param name
	 */
	private void addPage(TopLevelClass topLevelClass,
			IntrospectedTable introspectedTable, String name) {
		topLevelClass.addImportedType(new FullyQualifiedJavaType(
				"com.tgwoo.core.dao.pojo.Page"));
		CommentGenerator commentGenerator = context.getCommentGenerator();
		Field field = new Field();
		field.setVisibility(JavaVisibility.PROTECTED);
		field.setType(new FullyQualifiedJavaType("com.tgwoo.core.dao.pojo.Page"));
		field.setName(name);
		commentGenerator.addFieldComment(field, introspectedTable);
		topLevelClass.addField(field);
		char c = name.charAt(0);
		String camel = Character.toUpperCase(c) + name.substring(1);
		Method method = new Method();
		method.setVisibility(JavaVisibility.PUBLIC);
		method.setName("set" + camel);
		method.addParameter(new Parameter(new FullyQualifiedJavaType(
				"com.tgwoo.core.dao.pojo.Page"), name));
		method.addBodyLine("this." + name + "=" + name + ";");
		commentGenerator.addGeneralMethodComment(method, introspectedTable);
		topLevelClass.addMethod(method);
		method = new Method();
		method.setVisibility(JavaVisibility.PUBLIC);
		method.setReturnType(new FullyQualifiedJavaType(
				"com.tgwoo.core.dao.pojo.Page"));
		method.setName("get" + camel);
		method.addBodyLine("return " + name + ";");
		commentGenerator.addGeneralMethodComment(method, introspectedTable);
		topLevelClass.addMethod(method);
	}

	/**
	 * This plugin is always valid - no properties are required
	 */
	public boolean validate(List&lt;String&gt; warnings) {
		return true;
	}
}
</pre>
 
<p><span style="white-space: pre;">	</span>二、增加插件到Mybatis Generator配置文件中</p>
<p><span style="white-space: pre;">	</span><span style="white-space: pre; background-color: #fafafa;">&lt;?xml version="1.0" encoding="UTF-8" ?&gt;</span></p>
<pre class="xml" name="code">&lt;!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" &gt;
&lt;generatorConfiguration &gt;
	&lt;classPathEntry location="E:\work\eclipseWorkspace\myEclipse\CTSPMTS\WebRoot\WEB-INF\lib\ojdbc14.jar" /&gt;
	
	&lt;context id="oracle" &gt;
		&lt;plugin type="org.mybatis.generator.plugins.CaseInsensitiveLikePlugin"&gt;&lt;/plugin&gt;
	 	&lt;plugin type="org.mybatis.generator.plugins.SerializablePlugin"&gt;&lt;/plugin&gt;
	 	&lt;!-- Pagination --&gt;
	 	&lt;plugin type="com.tgwoo.core.dao.plugin.OraclePaginationPlugin"&gt;&lt;/plugin&gt;
	 	
	  	&lt;commentGenerator&gt;  
		   &lt;property name="suppressDate" value="true" /&gt;  
		    &lt;property name="suppressAllComments" value="true" /&gt;
	    &lt;/commentGenerator&gt;  
	  	
	    &lt;jdbcConnection driverClass="oracle.jdbc.driver.OracleDriver" connectionURL="jdbc:oracle:thin:@192.168.0.2:1521:ctspmt" userId="ctspmt" password="ctspmt123" /&gt;
	    &lt;javaModelGenerator targetPackage="com.tgwoo.ctspmt.model" targetProject="CTSPMTS/src" /&gt;
	    &lt;sqlMapGenerator targetPackage="com.tgwoo.ctspmt.data" targetProject="CTSPMTS/src" /&gt;
	    &lt;javaClientGenerator targetPackage="com.tgwoo.ctspmt.data" targetProject="CTSPMTS/src" type="XMLMAPPER" /&gt;&lt;!--
	  
	    &lt;table schema="ctspmt" tableName="mt_e_interface_log"/&gt;
	    --&gt;&lt;!--
	    &lt;table schema="ctspmt" tableName="mt_e_msg" /&gt;
	    &lt;table schema="ctspmt" tableName="mt_e_msg_log" /&gt;
	    &lt;table schema="ctspmt" tableName="mt_e_msg_receiver" /&gt;
	    &lt;table schema="ctspmt" tableName="st_e_org" /&gt;
	    &lt;table schema="ctspmt" tableName="st_e_role" /&gt;
	    &lt;table schema="ctspmt" tableName="st_e_user" /&gt;
	    &lt;table schema="ctspmt" tableName="mt_e_user_msg_conf" /&gt;
	    &lt;table schema="ctspmt" tableName="mt_j_user_device" /&gt;
	    &lt;table schema="ctspmt" tableName="st_j_user_role" /&gt;
	    &lt;table schema="ctspmt" tableName="ST_E_UNIQUE_KEY" /&gt;	 	
	 	--&gt;&lt;table schema="ctspmt" tableName="mt_v_msg_item" /&gt;
	 &lt;/context&gt;
	 
&lt;/generatorConfiguration&gt;</pre>
 
<p><span style="white-space: pre;">	</span></p>
<p><span style="white-space: pre;">	</span>三、示例</p>
<p><span style="white-space: pre;">	</span><span style="white-space: pre; background-color: #fafafa;">/**</span></p>
<pre class="java" name="code"> * Copyright (C) 2011 Tgwoo Inc.
 * http://www.tgwoo.com/
 */
package com.tgwoo.ctspmt.test;

import com.tgwoo.core.config.SpringBeanProxy;
import com.tgwoo.core.dao.pojo.Page;
import com.tgwoo.ctspmt.data.MtVMsgItemMapper;
import com.tgwoo.ctspmt.model.MtVMsgItemExample;

/**
 * @author pan.wei
 * @date 2011-11-25 下午01:26:17
 */
public class Test {
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		//get spring mapper instance 
		MtVMsgItemMapper mapper = SpringBeanProxy.getCtx().getBean(
				MtVMsgItemMapper.class);
		MtVMsgItemExample ex = new MtVMsgItemExample();
		Page page = new Page(0, 10);
		ex.setPage(page);
		ex.createCriteria().andMsgCodeEqualTo("222");
		// set count,up to you
		page.setCount(mapper.countByExample(ex));
		int row = mapper.selectByExample(ex).size();
		System.out.println("============row:" + row + "================");
	}

}
</pre>
 
<p><span style="white-space: pre;">	</span>四、分页类</p>
<p> </p>
<pre class="java" name="code">package com.tgwoo.core.dao.pojo;

/**
 * @author pan.wei
 * @date 2011-12-1 上午11:36:12
 */
public class Page {
	// 分页查询开始记录位置
	private int begin;
	// 分页查看下结束位置
	private int end;
	// 每页显示记录数
	private int length;
	// 查询结果总记录数
	private int count;
	// 当前页码
	private int current;
	// 总共页数
	private int total;

	public Page() {
	}

	/**
	 * 构造函数
	 * 
	 * @param begin
	 * @param length
	 */
	public Page(int begin, int length) {
		this.begin = begin;
		this.length = length;
		this.end = this.begin + this.length;
		this.current = (int) Math.floor((this.begin * 1.0d) / this.length) + 1;
	}

	/**
	 * @param begin
	 * @param length
	 * @param count
	 */
	public Page(int begin, int length, int count) {
		this(begin, length);
		this.count = count;
	}

	/**
	 * @return the begin
	 */
	public int getBegin() {
		return begin;
	}

	/**
	 * @return the end
	 */
	public int getEnd() {
		return end;
	}

	/**
	 * @param end
	 *            the end to set
	 */
	public void setEnd(int end) {
		this.end = end;
	}

	/**
	 * @param begin
	 *            the begin to set
	 */
	public void setBegin(int begin) {
		this.begin = begin;
		if (this.length != 0) {
			this.current = (int) Math.floor((this.begin * 1.0d) / this.length) + 1;
		}
	}

	/**
	 * @return the length
	 */
	public int getLength() {
		return length;
	}

	/**
	 * @param length
	 *            the length to set
	 */
	public void setLength(int length) {
		this.length = length;
		if (this.begin != 0) {
			this.current = (int) Math.floor((this.begin * 1.0d) / this.length) + 1;
		}
	}

	/**
	 * @return the count
	 */
	public int getCount() {
		return count;
	}

	/**
	 * @param count
	 *            the count to set
	 */
	public void setCount(int count) {
		this.count = count;
		this.total = (int) Math.floor((this.count * 1.0d) / this.length);
		if (this.count % this.length != 0) {
			this.total++;
		}
	}

	/**
	 * @return the current
	 */
	public int getCurrent() {
		return current;
	}

	/**
	 * @param current
	 *            the current to set
	 */
	public void setCurrent(int current) {
		this.current = current;
	}

	/**
	 * @return the total
	 */
	public int getTotal() {
		if (total == 0) {
			return 1;
		}
		return total;
	}

	/**
	 * @param total
	 *            the total to set
	 */
	public void setTotal(int total) {
		this.total = total;
	}

}
</pre>
<p> 五、生成后的代码</p>
<p>1、Example代码</p>
<p> </p>
<p> </p>
<pre class="java" name="code">package com.tgwoo.ctspmt.model;

import com.tgwoo.core.dao.pojo.Page;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

public class MtVMsgItemExample {
    protected String orderByClause;

    protected boolean distinct;

    protected List&lt;Criteria&gt; oredCriteria;

    protected Page page;
   
    ...</pre>
<p> 2、mapper.xml</p>
<p> </p>
<pre class="xml" name="code">...
 &lt;select id="selectByExample" resultMap="BaseResultMap" parameterType="com.tgwoo.ctspmt.model.MtVMsgItemExample" &gt;
    &lt;include refid="OracleDialectPrefix" /&gt;
    select
    &lt;if test="distinct" &gt;
      distinct
    &lt;/if&gt;
    &lt;include refid="Base_Column_List" /&gt;
    from CTSPMT.MT_V_MSG_ITEM
    &lt;if test="_parameter != null" &gt;
      &lt;include refid="Example_Where_Clause" /&gt;
    &lt;/if&gt;
    &lt;if test="orderByClause != null" &gt;
      order by ${orderByClause}
    &lt;/if&gt;
    &lt;include refid="OracleDialectSuffix" /&gt;
  &lt;/select&gt;
...
  &lt;sql id="OracleDialectPrefix" &gt;
    &lt;if test="page != null" &gt;
      select * from ( select row_.*, rownum rownum_ from ( 
    &lt;/if&gt;
  &lt;/sql&gt;
  &lt;sql id="OracleDialectSuffix" &gt;
    &lt;if test="page != null" &gt;
      &lt;![CDATA[ ) row_ ) where rownum_ &gt; #{page.begin} and rownum_ &lt;= #{page.end} ]]&gt;
    &lt;/if&gt;
  &lt;/sql&gt;
...
</pre>
 
<p> </p>
<p>附件是Mybatis Generatorjar包。</p>
<p>其他数据库的方言可以按照Oracle的去改写，有写好的希望能共享下。</p>
<p> </p>
<p> </p>
<p>-------------------------------------------------------------------------------------------------------</p>
<p>maven管理：</p>
<p>1、pom.xml</p>
<p>
</p>
<pre class="xml" name="code">&lt;build&gt;
		&lt;plugins&gt;
			&lt;plugin&gt;
				&lt;groupId&gt;org.mybatis.generator&lt;/groupId&gt;
				&lt;artifactId&gt;mybatis-generator-maven-plugin&lt;/artifactId&gt;
				&lt;version&gt;1.3.1&lt;/version&gt;
				&lt;executions&gt;
					&lt;execution&gt;
						&lt;id&gt;Generate MyBatis Artifacts&lt;/id&gt;
						&lt;goals&gt;
							&lt;goal&gt;generate&lt;/goal&gt;
						&lt;/goals&gt;
					&lt;/execution&gt;
				&lt;/executions&gt;
				&lt;dependencies&gt;
					&lt;dependency&gt;
						&lt;groupId&gt;com.oracle&lt;/groupId&gt;
						&lt;artifactId&gt;ojdbc14&lt;/artifactId&gt;
						&lt;version&gt;10.2.0.4.0&lt;/version&gt;
					&lt;/dependency&gt;
				&lt;/dependencies&gt;
			&lt;/plugin&gt;
		&lt;/plugins&gt;
	&lt;/build&gt;</pre>
 
<p> </p>
<pre class="xml" name="code">
</pre>
<p> </p>
<p> 2、generatorConfig.xml</p>
<p> </p>
<pre class="xml" name="code">&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;!DOCTYPE generatorConfiguration
  PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
  "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"&gt;
&lt;generatorConfiguration&gt;
	&lt;context id="oracleGenerator" targetRuntime="MyBatis3"&gt;
		&lt;plugin type="org.mybatis.generator.plugins.CaseInsensitiveLikePlugin"&gt;&lt;/plugin&gt;
		&lt;plugin type="org.mybatis.generator.plugins.SerializablePlugin"&gt;&lt;/plugin&gt;
		&lt;!-- Pagination --&gt;
		&lt;plugin
			type="com.tgwoo.test.core.dao.mybatis.generator.plugin.pagination.OraclePaginationPlugin"&gt;&lt;/plugin&gt;

		&lt;!-- 取消注释 --&gt;
		&lt;commentGenerator&gt;
			&lt;property name="suppressDate" value="true" /&gt;
			&lt;property name="suppressAllComments" value="true" /&gt;
		&lt;/commentGenerator&gt;
		&lt;!-- 配置连接数据信息 --&gt;
		&lt;jdbcConnection driverClass="oracle.jdbc.driver.OracleDriver"
			connectionURL="jdbc:oracle:thin:@192.168.0.2:1521:test" userId="test"
			password="test123" /&gt;
		&lt;javaTypeResolver&gt;
			&lt;property name="forceBigDecimals" value="false" /&gt;
		&lt;/javaTypeResolver&gt;

		&lt;!-- 配置自动生成的Model的保存路径与其它参数 --&gt;
		&lt;javaModelGenerator targetPackage="com.tgwoo.test.dao.model"
			targetProject=".\src\main\java"&gt;
			&lt;property name="enableSubPackages" value="false" /&gt;
			&lt;property name="trimStrings" value="true" /&gt;
		&lt;/javaModelGenerator&gt;

		&lt;!-- 配置自动生成的Mappper.xml映射的保存路径与其它参数 --&gt;
		&lt;sqlMapGenerator targetPackage="com.tgwoo.test.dao"
			targetProject=".\src\main\resources"&gt;
			&lt;property name="enableSubPackages" value="false" /&gt;
		&lt;/sqlMapGenerator&gt;

		&lt;!-- 配置自动生成的Mappper.java接口的保存路径与其它参数 --&gt;
		&lt;javaClientGenerator type="XMLMAPPER"
			targetPackage="com.tgwoo.test.dao" targetProject=".\src\main\java"&gt;
			&lt;property name="enableSubPackages" value="false" /&gt;
		&lt;/javaClientGenerator&gt;

		&lt;!-- 生成表对应的操作与实体对象 --&gt;
		&lt;table schema="test" tableName="testTable"&gt;
			&lt;columnOverride column="id" javaType="Long" /&gt;
		&lt;/table&gt;
	&lt;/context&gt;
&lt;/generatorConfiguration&gt;</pre>
<p> </p>
<p> 3、run</p>
<p>Goals:mybatis-generator:generate</p>
<p> </p>
<p>4、注意事项</p>
<p>报插件无法找到或者无法实例化的一般是分页插件和maven插件不在同一classloader下引起的，需要在mybatis-generator-maven-plugin的dependencies中增加dependency。</p>
  </div>

  
  <div class="attachments">
    
      
        <ul>
          <li><a href="http://dl.iteye.com/topics/download/9029591e-cb3c-3f09-a530-6fd039fe6e2e">mybatis-generator-core-1.3.1.jar</a> (470 KB)</li>
          
          <li>下载次数: 263</li>
        </ul>
      
    
    
  </div>



  
  
  <div id="bottoms" class="clearfix">
    
    <div id="share_weibo">分享到：
      <a data-type='sina' href="javascript:;" title="分享到新浪微博"><img src="/images/sina.jpg"></a>
      <a data-type='qq' href="javascript:;" title="分享到腾讯微博"><img src="/images/tec.jpg"></a>
    </div>
  </div>

  <div class="blog_nav">
    <div class="pre_next">
      <a href="/blog/1935246" class="next" title="Spring3 JmsTemplate与MQ的集成">Spring3 JmsTemplate与MQ的集成</a>
      |
      <a href="/blog/1180779" class="pre" title="使用get方法提交form表单时出现乱码解决方法">使用get方法提交form表单时出现乱码解决方 ...</a>
    </div>
  </div>
  <div class="blog_bottom">
    <ul>
      <li>2011-12-02 11:32</li>
      <li>浏览 6288</li>
      <li><a href="#comments">评论(11)</a></li>
      
      
      <li>分类:<a href="http://www.iteye.com/blogs/category/language">编程语言</a></li>      
      <li class='last'><a href="http://www.iteye.com/wiki/blog/1289274" target="_blank" class="more">相关推荐</a></li>
    </ul>
  </div>

  <div class="blog_comment">
    <h5>评论</h5>
    <a id="comments" name="comments"></a>
    <div id="bc2330564">
  <div class="comment_title">
    11 楼
    <a href='http://luoyongsir.iteye.com' target='_blank' title='luoyongsir'>luoyongsir</a>
    2013-11-06&nbsp;&nbsp;
    
    
  </div>
  <div class="comment_content"><div class="quote_title">yueai22 写道</div><div class="quote_div">唉。。我的报插件无法找到或者无法实例化。。。但是mybatis-generator-maven-plugin的dependencies中也增加dependency。但是还是报这个错。</div><br />哦我也是，你是怎么解决的？</div>
</div>

<div id="bc2330563">
  <div class="comment_title">
    10 楼
    <a href='http://luoyongsir.iteye.com' target='_blank' title='luoyongsir'>luoyongsir</a>
    2013-11-06&nbsp;&nbsp;
    
    
  </div>
  <div class="comment_content">我用的sql server 数据库，但是报：generate failed: Cannot instantiate object of type com.montnets.luoy.dao.plugins.PaginationPlugin 不知道有没有人解决了同样的问题的。</div>
</div>

<div id="bc2296345">
  <div class="comment_title">
    9 楼
    <a href='http://yueai22.iteye.com' target='_blank' title='yueai22'>yueai22</a>
    2013-01-06&nbsp;&nbsp;
    
    
  </div>
  <div class="comment_content">java.lang.RuntimeException: Cannot instantiate object of type xxxx.utils.OraclePaginationPlugin</div>
</div>

<div id="bc2296338">
  <div class="comment_title">
    8 楼
    <a href='http://yueai22.iteye.com' target='_blank' title='yueai22'>yueai22</a>
    2013-01-06&nbsp;&nbsp;
    
    
  </div>
  <div class="comment_content">唉。。我的报插件无法找到或者无法实例化。。。但是mybatis-generator-maven-plugin的dependencies中也增加dependency。但是还是报这个错。</div>
</div>

<div id="bc2292106">
  <div class="comment_title">
    7 楼
    <a href='http://qinlei-640-gmail-com.iteye.com' target='_blank' title='蜀山红日'>蜀山红日</a>
    2012-12-03&nbsp;&nbsp;
    
    
  </div>
  <div class="comment_content">oracle不支持rownum&lt;=?啊</div>
</div>

<div id="bc2268454">
  <div class="comment_title">
    6 楼
    <a href='http://duohuoteng.iteye.com' target='_blank' title='duohuoteng'>duohuoteng</a>
    2012-07-06&nbsp;&nbsp;
    
    
  </div>
  <div class="comment_content"><span style="color: white;"> cv</span></div>
</div>

<div id="bc2261257">
  <div class="comment_title">
    5 楼
    <a href='http://liqipan.iteye.com' target='_blank' title='panqili2120'>panqili2120</a>
    2012-05-28&nbsp;&nbsp;
    
    
  </div>
  <div class="comment_content">很强大 支持 呵呵，但在我们用的Page一般的begin是从1开始的， 也就是说上面的SQL的这部分也改成row_ ) where rownum_ &gt;= #{page.begin}这样</div>
</div>

<div id="bc2248739">
  <div class="comment_title">
    4 楼
    <a href='http://hgdakfg.iteye.com' target='_blank' title='hgdakfg'>hgdakfg</a>
    2012-03-21&nbsp;&nbsp;
    
    
  </div>
  <div class="comment_content"><div class="quote_title">hellostory 写道</div><div class="quote_div">如果是做【<span style="color: red;">高级查询</span>】分页显示，你这个如何实现？</div><br /><br />写视图.</div>
</div>

<div id="bc2243697">
  <div class="comment_title">
    3 楼
    <a href='http://chengfengmuyu.iteye.com' target='_blank' title='chengfengmuyu'>chengfengmuyu</a>
    2012-02-19&nbsp;&nbsp;
    
    
  </div>
  <div class="comment_content"><img src="/images/smiles/icon_twisted.gif" /> </div>
</div>

<div id="bc2242124">
  <div class="comment_title">
    2 楼
    <a href='http://daquan198163.iteye.com' target='_blank' title='daquan198163'>daquan198163</a>
    2012-02-08&nbsp;&nbsp;
    
    
  </div>
  <div class="comment_content">Good，太有用了！</div>
</div>

<div id="bc2241918">
  <div class="comment_title">
    1 楼
    <a href='http://hellostory.iteye.com' target='_blank' title='hellostory'>hellostory</a>
    2012-02-07&nbsp;&nbsp;
    
    
  </div>
  <div class="comment_content">如果是做【<span style="color: red;">高级查询</span>】分页显示，你这个如何实现？</div>
</div>


    
    
  </div>

  <div class="blog_comment">
    <h5>发表评论</h5>
            <p style="text-align:center; margin-top:30px;margin-bottom:0px;"><a href="/login" style="background-color:white;"> <img src="/images/login_icon.png" style="vertical-align:middle; margin-right: 10px;" /></a><a href="/login">  您还没有登录,请您登录后再发表评论 </a></p>
      </div>
</div>


<script type="text/javascript">
  dp.SyntaxHighlighter.HighlightAll('code', true, true);

  $$('#main .blog_content pre[name=code]').each(function(pre, index){ // blog content
    var post_id = 1289274;
    var location = window.location;
    source_url = location.protocol + "//" + location.host + location.pathname + location.search;
    pre.writeAttribute('codeable_id', post_id);
    pre.writeAttribute('codeable_type', "Blog");
    pre.writeAttribute('source_url', source_url);
    pre.writeAttribute('pre_index', index);
    pre.writeAttribute('title', 'Mybatis分页-利用Mybatis Generator插件生成基于数据库方言的分页语句，统计记录总数');
  });

  fix_image_size($$('div.blog_content img'), 700);

  function processComment() {
    $$('#main .blog_comment > div').each(function(comment){// comment
      var post_id = comment.id.substr(2);
      $$("#"+comment.id+" pre[name=code]").each(function(pre, index){
        var location = window.location;
        source_url = location.protocol + "//" + location.host + location.pathname + location.search;
        source_url += "#" + comment.id;
        pre.writeAttribute('codeable_id', post_id);
        pre.writeAttribute('codeable_type', "BlogComment");
        pre.writeAttribute('source_url', source_url);
        pre.writeAttribute('pre_index', index);
        pre.writeAttribute('title', 'Mybatis分页-利用Mybatis Generator插件生成基于数据库方言的分页语句，统计记录总数');
      });
    });
  }

  function quote_comment(id) {
    new Ajax.Request('/editor/quote', {
      parameters: {'id':id, 'type':'BlogComment'},
      onSuccess:function(response){editor.bbcode_editor.textarea.insertAfterSelection(response.responseText);
        Element.scrollTo(editor.bbcode_editor.textarea.element);}
    });
  }

  code_favorites_init();
  processComment();
  new WeiboShare({share_buttons: $('share_weibo'), img_scope: $('blog_content')});
</script>




        </div>

        <div id="local">
          <div class="local_top"></div>
          <div id="blog_owner">
  <div id="blog_owner_logo"><a href='http://ufopw.iteye.com'><img alt="ufopw的博客" class="logo" src="http://www.iteye.com/upload/logo/user/254087/32cfe11b-0b33-3a76-ab78-9f2e9bac7cb7.jpg?1274711258" title="ufopw的博客: 迷失代码" /></a></div>
  <div id="blog_owner_name">ufopw</div>
</div>

          <div id="blog_actions">
            <ul>
              <li>浏览: 45583 次</li>
              <li>性别: <img alt="Icon_minigender_1" src="http://www.iteye.com/images/icon_minigender_1.gif?1324994303" title="男" /></li>
              <li>来自: 合肥</li>
              <li><img src='/images/status/offline.gif'/></li>
              
            </ul>
          </div>
          <div id="user_visits" class="clearfix">
            <h5>最近访客 <span style='font-weight:normal;font-size:12px;padding-left:30px;'><a href="/blog/user_visits">更多访客&gt;&gt;</a></span></h5>
            
              <div class="user_visit">
                <div class="logo"><a href='http://idoves.iteye.com' target='_blank'><img alt="idoves的博客" class="logo" src="http://www.iteye.com/upload/logo/user/821511/19658123-4b87-395f-be1b-34277df6af04-thumb.jpg?1364189342" title="idoves的博客: " /></a></div>
                <div class="left"><a href='http://idoves.iteye.com' target='_blank' title='idoves'>idoves</a></div>
              </div>
            
              <div class="user_visit">
                <div class="logo"><a href='http://dylinshi126.iteye.com' target='_blank'><img alt="dylinshi126的博客" class="logo" src="http://www.iteye.com/images/user-logo-thumb.gif?1324994303" title="dylinshi126的博客: " /></a></div>
                <div class="left"><a href='http://dylinshi126.iteye.com' target='_blank' title='dylinshi126'>dylinshi126</a></div>
              </div>
            
              <div class="user_visit">
                <div class="logo"><a href='http://masz921-126-com.iteye.com' target='_blank'><img alt="lv双的博客" class="logo" src="http://www.iteye.com/images/user-logo-thumb.gif?1324994303" title="lv双的博客: " /></a></div>
                <div class="left"><a href='http://masz921-126-com.iteye.com' target='_blank' title='lv双'>lv双</a></div>
              </div>
            
              <div class="user_visit">
                <div class="logo"><a href='http://vs-diy.iteye.com' target='_blank'><img alt="vs_diy的博客" class="logo" src="http://www.iteye.com/images/user-logo-thumb.gif?1324994303" title="vs_diy的博客: vs_diy" /></a></div>
                <div class="left"><a href='http://vs-diy.iteye.com' target='_blank' title='vs_diy'>vs_diy</a></div>
              </div>
            
          </div>

          

                      <div id="blog_menu">
              <h5>文章分类</h5>
              <ul>
                <li><a href="/">全部博客 (64)</a></li>
                
                  <li><a href="/category/59841">Java (18)</a></li>
                
                  <li><a href="/category/59842">JavaScript (3)</a></li>
                
                  <li><a href="/category/59843">Sybase (1)</a></li>
                
                  <li><a href="/category/88490">Oralce (16)</a></li>
                
                  <li><a href="/category/109320">Websphere (2)</a></li>
                
                  <li><a href="/category/117622">Axis (6)</a></li>
                
                  <li><a href="/category/117624">Eclipse (1)</a></li>
                
                  <li><a href="/category/117631">JavaEE (9)</a></li>
                
                  <li><a href="/category/117632">设计模式 (1)</a></li>
                
                  <li><a href="/category/123104">项目管理 (1)</a></li>
                
                  <li><a href="/category/146824">数据结构与算法 (1)</a></li>
                
                  <li><a href="/category/151908">iOS (1)</a></li>
                
                  <li><a href="/category/152590">Android (5)</a></li>
                
                  <li><a href="/category/159788">Sqlite (1)</a></li>
                
                  <li><a href="/category/159823">Tomcat (2)</a></li>
                
                  <li><a href="/category/171061">版本控制 (1)</a></li>
                
              </ul>
            </div>
            <div id='month_blogs'>
              <h5>社区版块</h5>
              <ul>
                <li><a href="/blog/news">我的资讯</a> (0)</li>
                <li>
                  <a href="/blog/post">我的论坛</a> (30)
                </li>
                <li><a href="/blog/answered_problems">我的问答</a> (2)</li>
              </ul>
            </div>
            <div id="month_blogs">
              <h5>存档分类</h5>
              <ul>
                
                  <li><a href="/blog/monthblog/2013-09">2013-09</a> (2)</li>
                
                  <li><a href="/blog/monthblog/2011-12">2011-12</a> (1)</li>
                
                  <li><a href="/blog/monthblog/2011-09">2011-09</a> (2)</li>
                
                <li><a href="/blog/monthblog_more">更多存档...</a></li>
              </ul>
            </div>
            
            

            <div id="guest_books">
              <h5>最新评论</h5>
              <ul>
                
                <li>
                  <a href='http://luoyongsir.iteye.com' target='_blank' title='luoyongsir'>luoyongsir</a>： 
                  &lt;div class=&quot;quote_title ...<br />
                  <a href="/blog/1289274#bc2330564">Mybatis分页-利用Mybatis Generator插件生成基于数据库方言的分页语句，统计记录总数</a>
                </li>
                
                <li>
                  <a href='http://luoyongsir.iteye.com' target='_blank' title='luoyongsir'>luoyongsir</a>： 
                  我用的sql server 数据库，但是报：generate  ...<br />
                  <a href="/blog/1289274#bc2330563">Mybatis分页-利用Mybatis Generator插件生成基于数据库方言的分页语句，统计记录总数</a>
                </li>
                
                <li>
                  <a href='http://yueai22.iteye.com' target='_blank' title='yueai22'>yueai22</a>： 
                  java.lang.RuntimeException: Can ...<br />
                  <a href="/blog/1289274#bc2296345">Mybatis分页-利用Mybatis Generator插件生成基于数据库方言的分页语句，统计记录总数</a>
                </li>
                
                <li>
                  <a href='http://yueai22.iteye.com' target='_blank' title='yueai22'>yueai22</a>： 
                  唉。。我的报插件无法找到或者无法实例化。。。但是mybatis ...<br />
                  <a href="/blog/1289274#bc2296338">Mybatis分页-利用Mybatis Generator插件生成基于数据库方言的分页语句，统计记录总数</a>
                </li>
                
                <li>
                  <a href='http://qinlei-640-gmail-com.iteye.com' target='_blank' title='蜀山红日'>蜀山红日</a>： 
                  oracle不支持rownum&amp;lt;=?啊<br />
                  <a href="/blog/1289274#bc2292106">Mybatis分页-利用Mybatis Generator插件生成基于数据库方言的分页语句，统计记录总数</a>
                </li>
                
              </ul>
            </div>

            <div class="local_bottom"></div>
          
        </div>
      </div>

      <div id="footer" class="clearfix">
        <div id="copyright">
          <hr/>
          声明：ITeye文章版权属于作者，受法律保护。没有作者书面许可不得转载。若作者同意转载，必须以超链接形式标明文章原始出处和作者。<br />
          &copy; 2003-2012 ITeye.com.   All rights reserved.  [ 京ICP证110151号  京公网安备110105010620 ]
        </div>
      </div>
    </div>
    <script type="text/javascript">
  document.write("<img src='http://stat.iteye.com/?url="+ encodeURIComponent(document.location.href) + "&referrer=" + encodeURIComponent(document.referrer) + "&user_id=' width='0' height='0' />");
</script>

<script src="http://csdnimg.cn/pubfooter/js/tracking.js?version=20130923164150" type="text/javascript"></script>

    
<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', '']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>
      
    
  </body>
</html>
